#!/bin/bash

KE_JAVA_OPTS="-server -Xmx2g -Xms2g -XX:MaxGCPauseMillis=20 -XX:+UseG1GC -XX:MetaspaceSize=128m -XX:InitiatingHeapOccupancyPercent=35 -XX:G1HeapRegionSize=16M -XX:MinMetaspaceFreeRatio=50 -XX:MaxMetaspaceFreeRatio=80"

stime=`date "+%Y-%m-%d %H:%M:%S"`

COLOR_G="\x1b[0;32m"  # green
COLOR_R="\x1b[1;31m"  # red
RESET="\x1b[0m"

echo -n [$stime] INFO: $"Starting "
echo "EFAK( Eagle For Apache Kafka ) environment check ..."

if [ "$KE_HOME" = "" ]; then
 echo "[$stime] Error: The KE_HOME environment variable is not defined correctly."
 echo "[$stime] Error: This environment variable is needed to run this program."
 exit 1
fi

if [ "$JAVA_HOME" = "" ]; then
 echo "[$stime] Error: The JAVA_HOME environment variable is not defined correctly."
 echo "[$stime] Error: This environment variable is needed to run this program."
 exit 1
fi

if [ ! -d "/data/ke/sqlite" ]; then
 echo -e "[$stime] Error: The $COLOR_G/data/ke/sqlite$RESET directory for sqlite is not exist."
 echo "[$stime] Error: This directory is needed to run this program."
 exit 1
fi

PID=`ps -ef | grep ${KE_HOME}/ | grep -v grep | grep KafkaEagle | awk '{print $2}'`

if [ -n "$PID" ]; then
 echo "[$stime] Error: The EFAK[$PID] has started."
 exit 1
fi

bin=`dirname "$0"`
KE_HOME=`cd $bin/../; pwd`
KE_HOME_CONF_DIR=$KE_HOME/conf/
DIALUP_PID=$KE_HOME/bin/ke.pid
CLASSPATH="${KE_HOME}":"${KE_HOME_CONF_DIR}"
for i in ${KE_HOME}/*.jar; do
  CLASSPATH=${CLASSPATH}:$i
done
echo -n [$stime] INFO: $"CLASSPATH: "
echo ${CLASSPATH}

LOG_DIR=${KE_HOME}/logs/ke-spring-boot.out
cd ${KE_HOME}

nohup ${JAVA_HOME}/bin/java $KE_JAVA_OPTS -cp ${CLASSPATH} org.springframework.boot.loader.JarLauncher > ${LOG_DIR} 2>&1 &

sleep 3s
KE_PID=`ps -ef | grep ${KE_HOME}/ | grep -v grep | awk '{print $2}'`
echo "*******************************************************************"
if [ -n "$KE_PID" ]; then
  ps -ef | grep ${KE_HOME}/ | grep -v grep | awk '{print $2}' > $DIALUP_PID
  ADMIN="Account:admin, Password:123456"
  echo "* EFAK Service has started success."
  echo -e "* "$COLOR_G$ADMIN$RESET
else
  echo "* EFAK Service has started failed."
  echo -e "* Check the log file for details: "$COLOR_G$LOG_DIR$RESET
fi
echo "*******************************************************************"
